package com.devicemantra.coordinate.ds.tests;
import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.devicemantra.coordinate.dataobjects.CState;
import com.devicemantra.coordinate.dataobjects.CStateFactory;
import com.devicemantra.coordinate.exceptions.dataobjects.CDatabaseException;
import com.devicemantra.coordinate.exceptions.operations.CStateAlreadyExistsException;

@SuppressWarnings("serial")
public class AddState extends HttpServlet 
{
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
	{
		//resp.setContentType("text/html");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		/* Check whether a department exists with the same name */
		if(CStateFactory.checkStateExists(req.getParameter("state_name")))
		{
			//resp.getOutputStream().println("[State Check failed] <BR> ");
		}
		else
		{
			//resp.getOutputStream().println("[State Check passed] <BR>");
		}
		
		
		CState lState = null;
		try {
				CStateFactory.createNewState(req.getParameter("state_name"));
		} catch (CStateAlreadyExistsException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		catch (CDatabaseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if( lState != null)
		{
			pm.makePersistent(lState);
			pm.close();
			//resp.getOutputStream().print("State Added " + lState.getName());
		}
		else
		{
			//resp.getOutputStream().print("State with that name already exists ");
		}
		List<CState> lStateList = CStateFactory.getAllStates();
		try
		{
			RequestDispatcher lDispatcher = req.getRequestDispatcher("/modules/administration/states.jsp");
			if( lDispatcher == null )
			{
				System.out.println("DISPATCHER WAS NULL");
			}
			else
			{
				System.out.println("DISPATCHER WAS [NOT] NULL");
				req.setAttribute("STATE_LIST", lStateList);
				lDispatcher.forward(req,resp);
			}
			
		} catch(Exception e) { e.printStackTrace(); }
	}
}
